<template>
  <base-panel
    :show.sync="visible"
    :width="panelWidth"
    @close="handleClose"
    :re="true"
    class="customize-filter-view-panel"
  >
    <!-- 标题 -->
    <h3 slot="title">
      <span class="title">{{ title }}</span>
      <el-dropdown class="pull-right" trigger="click" @command="setColumn">
        <i class="iconfont icon-xitongguanli"></i>

        <el-dropdown-menu slot="dropdown" class="customer-advance-setting">
          <el-dropdown-item command="1">{{$t('common.base.table.oneCl')}}</el-dropdown-item>
          <el-dropdown-item command="2">{{$t('common.base.table.twoCl')}}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </h3>
    <div class="view-panel-container">
      <div class="view-panel-content">
        <div class="view-name">
          <span>{{$t('customer.components.customizeFilterView.type.name')}}</span>
          <el-input
            v-model="view.name"
            :placeholder="$t('customer.components.customizeFilterView.placeholder.name')"
            :disabled="type === 'view'"
            :maxlength="maxlength"
          ></el-input>
        </div>

        <div class="task-pointer task-flex task-ai">
          <span class="task-font16 task-mr4">{{$t('customer.components.customizeFilterView.tips.tip5')}}</span>
          <span>
            <el-tooltip
              :content="$t('customer.components.customizeFilterView.tips.tip5')"
              placement="top"
            >
              <i class="iconfont icon-question task-icon"></i>
            </el-tooltip>
          </span>
        </div>

        <inquire
          v-if="searchModelCN.length"
          ref="inquireRef"
          :type="type"
          :column-num="columnNum"
          :config="inquireList"
          :task-nums="searchModelCN"
        />

        <el-checkbox
          v-if="type !== 'view'"
          v-model="view.fullShowed"
          class="view-region"
        >
          {{$t('customer.components.customizeFilterView.btns.btn3')}}
        </el-checkbox>
      </div>

      <div class="view-panel-footer" slot="footer">
        <el-button @click="handleClose">{{$t('common.base.cancel')}}</el-button>
        <el-button
          v-if="type !== 'view'"
          type="primary"
          @click="handleSaveView"
        >
          {{$t('customer.components.customizeFilterView.btns.btn4')}}
        </el-button>
      </div>
    </div>
  </base-panel>
</template>

<script>
import _ from 'lodash';
import Inquire from './Inquire.vue';

/* utils */
import { formatDate } from 'pub-bbx-utils';
import { isEmptyStringObject } from '@src/util/function';
import * as Utils from '@src/component/form/util';
import { matchOperator,
  getSimpleCustomerList,
  getSimpleTagListByIds,
  getSimpleUserListByIds,
  getSimpleProductList,
  getLinkmanListByIds } from './common.js';

/* constants */
import { TaskOnceConvertMap, TaskApproveConvertMap } from '@src/modules/task/model/TaskConvertMap.ts';

const MultiFieldNames = [
  'serviceType',
  'serviceContent',
  'level',
  'state',
  'tag',
];

const InquireConvertFieldNamesToConditionsMap = {
  customer: 'customerId',
  product: 'productId',
  tlmName: 'tlmId',
};

// 人员相关字段
const UserFieldMap = [
  'createUser', // 创建人
  'allotUser', // 派单人
  'executorUser', // 负责人
  'customerManager', // 客户负责人
  'user', // 人员
  'synergies' // 协同人
]

export default {
  name: 'customize-filter-view-panel',
  props: {
    fields: {
      type: Array,
      default: () => [],
    },
    model: {
      type: String,
      default: 'customize-filter',
    },
    maxlength: {
      type: Number,
      default: 20,
    },
  },
  data() {
    return {
      columnNum: 1,
      visible: false,
      type: 'create',
      view: {
        name: '',
        searchModel: {},
        fullShowed: false,
      },
      title: this.$t('customer.components.customizeFilterView.title.title1'),
      searchModelCN: [],
    };
  },
  watch: {},
  computed: {
    panelWidth() {
      return `${420 * this.columnNum}px`;
    },
    inquireList() {
      return this.fields;
    },
    storageKey() {
      return `${this.model}-view-panel-column-num`;
    },
  },
  methods: {
    // 打开本视图抽屉组件
    async open(type, viewData) {
      console.log('open view panel', viewData);
      this.type = type;
      this.columnNum = Number(localStorage.getItem(this.storageKey)) || 1;
      this.initViewData(viewData);
      this.visible = true;

      const { systemConditions = [], conditions = [] } =
        viewData?.searchModel || {};
      await this.getOneView([...systemConditions, ...conditions]);
    },

    // 设置视图排版 1列or2列
    setColumn(command) {
      this.columnNum = Number(command);
      localStorage.setItem(this.storageKey, this.columnNum);
    },

    // 保存视图
    handleSaveView() {
      if (!this.view.name) return this.$message.warning(this.$t('customer.components.customizeFilterView.tips.tip7'));

      const { view } = this;

      // 用于回显的数据
      // TODO 待优化
      const { systemConditions, conditions } = this.buildInquireParams();
      view.searchModel = {
        ...view.searchModel,
        ...{ systemConditions, conditions },
      };

      // 用于搜索的数据
      view.inquireForm = { ...this.$refs.inquireRef.returnData() };

      this.searchModelCN = [];

      this.$emit('save', this.type, view);
    },

    handleClose() {
      this.visible = false;
      this.$emit('close');
    },

    // 初始化视图数据
    initViewData(viewData) {
      if (this.type === 'create') {
        this.title = this.$t('customer.components.customizeFilterView.title.title1');
        this.view = {
          name: '',
          searchModel: {},
          fullShowed: false,
        };
      } else {
        this.view = viewData;
        this.title = viewData?.name || this.$t('customer.components.customizeFilterView.title.title2');
      }
    },

    // 是否需要处理值用于inquire组件回显
    isConditionItemNeedFormat(item, value) {
      return (
        item.property === value.fieldName
          || item.property === value.englishName
          || (item.property === 'customerId' && value.fieldName === 'customer') // 客户
          || (item.property === 'tlmId' && (value.fieldName === 'tlmName' || value.fieldName === 'linkmanId')) // 联系人
          || (item.property === 'productId' && value.fieldName === 'product') // 产品
          || (item.property === 'executorUser' && value.fieldName === 'executor') // 负责人
          || (item.property === 'synergies' && value.fieldName === 'synergyId') // 协同人
          || ((item.property === 'province' || item.property === 'city' || item.property === 'dist') && value.fieldName === 'area') // 省市区
          || (item.property === 'tagIds' && value.fieldName === 'tags') // 团队
      )       
    },

    /**
     * 查看视图
     */
    async getOneView(allConditions) {
      let initObj = {
        key: '',
        content: '',
        fieldName: '',
        formType: '',
      }
      if (!allConditions || !allConditions.length) {
        this.searchModelCN = [initObj];
        return;
      }

      let address;
      this.searchModelCN = [];
      const fieldList = _.cloneDeep(this.fields);

      for await(const item of allConditions) {
        let originObj;
        let isAddress = false;
        for await(const field of fieldList) {
          // 对客户、联系人、产品、负责人、协同人、省市区域、团队字段做特殊处理
          const isNeedFormat = this.isConditionItemNeedFormat(item, field);
          if (isNeedFormat) {
            originObj = {
              key: field.displayName,
              content: item.value,
              fieldName: field.fieldName,
              formType: field.formType,
              operatorValue: item.operator || '',
            }

            const property = field.isSystem ? item.property : field.formType;
            /** --------数组类型-------- **/
            if (item.inValue) {
              if (UserFieldMap.indexOf(property) >= 0) {
                // 如果是key是人员相关的字段 value通过调取以下接口获取返回值
                await getSimpleUserListByIds(item.inValue, content => {
                  originObj.content = content;
                  originObj.ids = item.inValue;
                });
              } else if (property === 'tagIds') {
                // 团队
                await getSimpleTagListByIds(item.inValue, res => {
                  originObj.content = res
                    .map(item => {
                      return item.tagName;
                    })
                    .join('，');
                  originObj.ids = item.inValue;
                });
              } else {
                originObj.content = item.inValue.join('，');
                originObj.setting = field.setting;
                originObj.isSystem = field.isSystem;
              }
            } 
            /** --------时间类型-------- **/
            else if (item.betweenValue1) {
              const value1Str = item.betweenValue1.split('-').join('/');
              const value2Str = item.betweenValue2.split('-').join('/');
              originObj.content = `${value1Str} - ${value2Str}`;
            } 
            /** --------字符串类型-------- **/
            else {
              if (property === 'province' || property === 'city' || property === 'dist') {
                // 省市地区
                if(property === 'province') {
                  address = {
                    key: field.displayName,
                    fieldName: 'area',
                    formType: field.formType || 'address',
                  };
                }
                address[property] = item.value;
                isAddress = true;
              } else if (property === 'customerId') {
                // 客户
                await getSimpleCustomerList([item.value], ({ name }) => {
                  originObj.content = name;
                  originObj.id = item.value;
                });
              } else if (property === 'productId') {
                // 产品
                await getSimpleProductList([item.value], ({ name }) => {
                  originObj.content = name;
                  originObj.id = item.value;
                });
              } else if (property === 'tlmId' || property === 'linkmanId') {
                // 联系人
                await getLinkmanListByIds([item.value], ({ name }) => {
                  originObj.content = name;
                  originObj.id = item.value;
                });
              } else if (UserFieldMap.indexOf(property) >= 0) {
                // 单选人员
                await getSimpleUserListByIds([item.value], content => {
                  originObj.content = content;
                  originObj.id = item.value;
                });
              }
            }
          }
        }
        if(originObj && !isAddress) this.searchModelCN.push(originObj);
      }
      // address是需要根据多个字段整合的，所以在最后push
      if(address) this.searchModelCN.push(address);
    },

    // 构建inquire组件需要的数据 （拷贝的工单模块的，有的用不到或者需要改动，暂时没动
    buildInquireParams() {
      let params = {
        systemConditions: [],
        conditions: [],
      };
      const inquireList = this.$refs.inquireRef.returnInquireFields();
      const form = { ...this.$refs.inquireRef.returnData() };

      const isSystemFields = inquireList.filter(f => f.isSystem);
      const notSystemFields = inquireList.filter(f => !f.isSystem);

      let tv = null;
      let fn = '';
      // 固定条件
      for (let i = 0; i < isSystemFields.length; i++) {
        tv = isSystemFields[i];
        fn = tv.fieldName;
        const isMulti = Utils.isMultiField(tv);
        if ((!form[fn] && form[fn] !== 0) || (Array.isArray(form[fn]) && !form[fn].length)) {
          continue;
        }

        // 空对象
        if (
          typeof form[fn] === 'object' &&
          !Array.isArray(form[fn]) &&
          !Object.keys(form[fn]).length
        ) {
          continue;
        }

        if (tv.formType === 'address' || tv.formType === 'area') {
          let address = [];
          let isEmpty = isEmptyStringObject(form[fn]);

          if (!isEmpty) {
            const province = form[fn].province || form[fn][0];
            if (province) {
              address.push({
                property: 'province',
                operator: tv.operatorValue,
                value: province,
              });
            }
            const city = form[fn].city || form[fn][1];
            if (city) {
              address.push({
                property: 'city',
                operator: tv.operatorValue,
                value: city,
              });
            }
            const dist = form[fn].dist || form[fn][2];
            if (dist) {
              address.push({
                property: 'dist',
                operator: tv.operatorValue,
                value: dist,
              });
            }
          }
          params.systemConditions = [...params.systemConditions, ...address];
          continue;
        }

        if (tv.fieldName == 'tags') {
          let condition = {
            property: 'tagIds',
            operator: tv.operatorValue,
            inValue: form[fn].map(tag => {
              return tag.id;
            }),
          };
          params.systemConditions.push(condition);
          continue;
        }

        if (tv.fieldName == 'product') {
          params.systemConditions.push({
            property: 'productId',
            operator: tv.operatorValue,
            value: form[fn],
          });
          continue;
        }

        if (tv.fieldName === 'synergyId') {
          let condition = {
            property: 'synergies',
            operator: tv.operatorValue,
            inValue: form[fn],
          };
          params.systemConditions.push(condition);
          continue;
        }

        if (['date', 'datetime'].includes(tv.formType)) {
          params.systemConditions.push({
            property: fn,
            operator: tv.operatorValue,
            betweenValue1: form[fn][0],
            betweenValue2: form[fn][1],
          });
          continue;
        }

        if (tv.fieldName === 'executor') {
          params.systemConditions.push({
            property: 'executorUser',
            operator: tv.operatorValue,
            inValue: form[fn],
          });
          continue;
        }

        if (
          MultiFieldNames.indexOf(tv.formType) !== -1 ||
          tv.formType === 'user'
        ) {
          const tempObj = {
            property: fn,
            operator: tv.operatorValue,
          }
          // 单选value 多选inValue
          tempObj[isMulti ? 'inValue' : 'value'] = form[fn];

          params.systemConditions.push(tempObj);
          continue;
        }

        if (InquireConvertFieldNamesToConditionsMap[fn]) {
          params.systemConditions.push({
            property: InquireConvertFieldNamesToConditionsMap[fn],
            operator: tv.operatorValue,
            value: form[fn],
          });
          continue;
        }

        let value =
          TaskOnceConvertMap[form[fn]] != undefined
            ? TaskOnceConvertMap[form[fn]]
            : form[fn];
        value =
          TaskApproveConvertMap[value] != undefined
            ? TaskApproveConvertMap[value]
            : value;

        params.systemConditions.push({
          property: fn,
          operator: tv.operatorValue,
          value,
        });
      }

      // 自定义条件
      for (let i = 0; i < notSystemFields.length; i++) {
        tv = notSystemFields[i];
        fn = tv.fieldName;
        !tv.operator ? (tv['operator'] = matchOperator(tv)) : '';
        if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
          continue;
        }

        // 空对象
        if (
          typeof form[fn] === 'object' &&
          !Array.isArray(form[fn]) &&
          !Object.keys(form[fn]).length
        ) {
          continue;
        }

        // FIXME: 同下面 datetime
        if (tv.formType === 'date') {
          params.conditions.push({
            property: fn,
            operator: tv.operator,
            betweenValue1: formatDate(form[fn][0], 'YYYY-MM-DD HH:mm:ss'),
            betweenValue2: `${formatDate(form[fn][1], 'YYYY-MM-DD')} 23:59:59`,
          });
          continue;
        }

        if (tv.formType === 'cascader') {
          params.conditions.push({
            property: fn,
            operator: tv.operator,
            inValue: form[fn],
          });
          continue;
        }

        if (tv.formType === 'user' && Array.isArray(form[fn])) {
          params.conditions.push({
            property: fn,
            operator: 'user',
            inValue: form[fn],
          });
          continue;
        }

        // FIXME: 这里 form[fn] 为 字 符串的时候 error
        if (tv.formType === 'datetime') {
          params.conditions.push({
            property: fn,
            operator: tv.operator,
            betweenValue1: formatDate(form[fn][0], 'YYYY-MM-DD HH:mm:ss'),
            betweenValue2: `${formatDate(form[fn][1], 'YYYY-MM-DD')} 23:59:59`,
          });
          continue;
        }
        params.conditions.push({
          property: fn,
          operator: tv.operator,
          value: form[fn],
        });
      }
      const { systemConditions, conditions } = params;
      if (!systemConditions.length && !conditions.length) {
        this.$platform.alert(this.$t('customer.components.customizeFilterView.tips.tip8'));
        return;
      }
      this.searchModelCN = [];
      return params;
    },
  },
  components: {
    [Inquire.name]: Inquire,
  },
};
</script>

<style lang="scss" scoped>
.customize-filter-view-panel {
  .title {
    max-width: 80%;
    display: inline-block;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
  .view-panel-container {
    position: relative;
    overflow: hidden;
    padding: 10px 15px 63px 15px;
    height: calc(100% - 52px);

    .view-panel-content {
      overflow: auto;
      height: calc(100% - 30px);
      .view-name {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 15px 15px 20px 0;
        > span {
          min-width: 85px;
        }
        > div {
          width: 225px;
        }
      }
      .view-region {
        position: absolute;
        bottom: 62px;
      }
      .view-panel-view {
        display: flex;
        flex-wrap: wrap;
        padding: 15px 15px 0;
        span {
          display: inline-block;
          min-width: 85px;
        }
        > div {
          display: inline-block;
          width: 225px;
        }
      }
    }
    .view-panel-footer {
      display: flex;
      justify-content: flex-end;
      width: 100%;
      position: absolute;
      bottom: 0px;
      background: #fff;
      padding: 15px 20px;
      margin-left: -15px;
    }
  }
}
</style>
